/*
 * @Descripttion:
 * @version:
 * @Author: cxguo
 * @Date: 2020-04-04 10:52:10
 * @LastEditors: cxguo
 * @LastEditTime: 2020-06-12 11:00:48
 */

import { amount } from '@/libs/tools.js'

export const getPriceData = function(unitData, originPriceData, priceType) {
  const priceData = originPriceData
  const result = []
  unitData.forEach(item => {
    if (item.value) {
      const obj = { unitId: item.value, unitName: item.label }
      const price = {}
      priceType.forEach((type, index) => {
        const row = priceData[index]
        price[type.value] = row[item.value]
      })
      obj.price = JSON.stringify(price)
      result.push(obj)
    }
  })
  return result
}

/**
 * 初始化默认的priceData
 */
export const initDefaultPriceData = function(priceType, unitData) {
  return initPriceData(priceType, unitData)
}

export const initUpdatePriceData = function(priceType, unitData, goodspriceList) {
  return initPriceData(priceType, unitData, goodspriceList)
}

function initPriceData(priceType, unitData, goodspriceList) {
  const result = []
  priceType.forEach((item) => {
    const priceValueFiled = { priceCat: item.value, priceCatName: item.label }
    const priceValueFileds = getPriceValuesByUnits(item.value, unitData, goodspriceList)
    const obj = { ...priceValueFiled, ...priceValueFileds }
    result.push(obj)
  })
  return result
}

function getPriceValuesByUnits(priceValue, unitData, goodspriceList) {
  const obj = {}
  unitData.forEach(item => {
    obj[item.value] = getPriceByUnitAndPriceType(priceValue, item.value, goodspriceList)
  })
  return obj
}

/**
 * 根据unitId, priceType获取价格
 */
function getPriceByUnitAndPriceType(priceValue, unitValue, goodspriceList) {
  const defaultValue = amount(0).format()
  if (!goodspriceList) return defaultValue
  const unitObj = goodspriceList.find(item => { return item.unitId === unitValue })
  if (!unitObj) return defaultValue
  const priceObj = JSON.parse(unitObj.price)
  return priceObj[priceValue]
}
